package org.csu.mypetstore.api.controller.front;


import org.csu.mypetstore.api.Vo.AccountVO;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/account/")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @PostMapping("login")
    @ResponseBody
    public CommonResponse<AccountVO> login(
            @RequestParam String username,
            @RequestParam String password,
            HttpSession session){
        CommonResponse<AccountVO> response = accountService.getAccount(username,password);
        if(response.isSuccess()){
            session.setAttribute("login_account" , response.getData());
        }
        return response;
    }

    @PostMapping("get_login_account_info")
    @ResponseBody
    public CommonResponse<AccountVO> getLoginAccountInfo(HttpSession session){
        AccountVO loginAccount = (AccountVO)session.getAttribute("login_account");
        if(loginAccount != null){
            return CommonResponse.createForSuccess(loginAccount);
        }
        //return CommonResponse.createForError(ResponseCode.NEED_LOGIN.getCode(), "用户未登录，不能获取用户信息");
        return CommonResponse.createForError("用户未登录，不能获取用户信息");
    }

    @PutMapping()
    @ResponseBody
    public CommonResponse<AccountVO> updateAccount(
            @RequestParam String username,
            @RequestParam AccountVO accountVO){
        return accountService.updateAccount(username,accountVO);
    }

    @DeleteMapping()
    @ResponseBody
    public CommonResponse<AccountVO> signOff(@PathVariable("id")String username){
        return CommonResponse.createForSuccessMessage("退出成功");
    }

    //注册 新增账号 跳转交给前端
    @PostMapping()
    @ResponseBody
    public CommonResponse<AccountVO> register(AccountVO accountVo){
        return accountService.insertAccount(accountVo);
    }

}